package com.company.jetpack.work;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.work.Data;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

/**
 * author : dingqb
 * e-mail : dingqb@sany.com.cn
 * date   : 2020/11/20 2:31 PM
 * desc   :
 * version: 1.0
 */
public class SecondWorker extends Worker {
    public static final String KEY = "key";
    private String TAG = "ReadSecondWorker";
    public static final String PROGRESS = "PROGORESS";
    public int[] values;

    public SecondWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
        Log.e(TAG, "SecondWorker: ");
        values = getInputData().getIntArray(KEY);
    }

    @SuppressLint("RestrictedApi")
    @NonNull
    @Override
    public Result doWork() {
        Log.e(TAG, "doWork: " + Thread.currentThread().getName());
        int i = 0;
        while (isRunning) {
            if (isStopped()){
                isRunning=false;
            }
            i++;
            Log.e(TAG, "readSecond: " + i + " ,isStopped==" + isStopped()+",isRunInForeground=="+isRunInForeground()+", isUsed=="+isUsed());
            // 异步更新进度
            setProgressAsync(new Data.Builder().putInt(PROGRESS, i).build());
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        if (isStopped()){
            isRunning=false;
            return Result.success();
        }
        Data data = new Data.Builder().putIntArray(KEY, values).build();
        return Result.success(data);
    }

    boolean isRunning = true;

    private void readSecond() throws InterruptedException {


    }

}
